import subprocess
import time
import constant as con

def singleton(cls):
    """
    单例装饰器
    :param cls:
    :return:
    """
    instances = {}

    def _singleton(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]

    return _singleton


@singleton
class ProxyClient(object):

    def __init__(self, proxy_client_path, proxy_client_suffix=con.PROXY_CLIENT_SUFFIX):
        self.proxy_client_path = proxy_client_path
        self.proxy_client_suffix = proxy_client_suffix
        self.cmd = proxy_client_path + proxy_client_suffix
        print(self.cmd)
        self.proxy_client = subprocess.Popen(self.cmd, shell=True)
        time.sleep(1)
        if self.proxy_client.poll():
            self.restart_proxy_client()

    def restart_proxy_client(self):
        if self.proxy_client.poll():
            self.stop_proxy_client()
            self.proxy_client = subprocess.Popen(self.cmd, shell=True)
            time.sleep(1)

    def stop_proxy_client(self):
        # if not self.proxy_client.poll():
        #     self.proxy_client.terminate()
        # windows 下强制杀掉gost进程
        subprocess.Popen("taskkill /im gost.exe /f", shell=True)
        time.sleep(0.5)

    def __del__(self):
        self.stop_proxy_client()


def api_key_decryption(api_key, api_secret):
    # ToDO 后面增加对api的加密和解密功能
    return api_key, api_secret




